package com.seeyon.v3x.mail.usermessage.pipeline;

import java.util.Iterator;
import java.util.List;
import java.util.Locale;
import java.util.ResourceBundle;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.apache.commons.lang3.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import com.seeyon.apps.kk.manager.KkEmailStrongManager;
import com.seeyon.ctp.common.AppContext;
import com.seeyon.ctp.common.authenticate.domain.User;
import com.seeyon.ctp.common.i18n.ResourceBundleUtil;
import com.seeyon.ctp.common.i18n.ResourceUtil;
import com.seeyon.ctp.common.usermessage.Constants;
import com.seeyon.ctp.common.usermessage.pipeline.Message;
import com.seeyon.ctp.common.usermessage.pipeline.MessagePipeline;
import com.seeyon.ctp.organization.manager.OrgManager;
import com.seeyon.ctp.organization.manager.OrgManagerDirect;
import com.seeyon.ctp.util.Strings;
import com.seeyon.v3x.mail.manager.MessageMailManager;

/**
 * 邮件消息通道
 */
public class MailMessagePipeline implements MessagePipeline {

    private static final Log log = LogFactory.getLog(MailMessagePipeline.class);

    private MessageMailManager messageMailManager;
    private OrgManager orgManager;
    private OrgManagerDirect orgManagerDirect;

    public void setMessageMailManager(MessageMailManager messageMailManager) {
        this.messageMailManager = messageMailManager;
    }

    public void setOrgManager(OrgManager orgManager) {
        this.orgManager = orgManager;
    }

    public void setOrgManagerDirect(OrgManagerDirect orgManagerDirect) {
        this.orgManagerDirect = orgManagerDirect;
    }

    public void invoke(Message[] messages) {
        if (!messageMailManager.hasSystemMailbox()) {
            return;
        }
        boolean isSendOnline = messageMailManager.getSysEMailConfig().isSendOnline();
        for (Message message : messages) {
            if (message.isReceiverOnline() && !isSendOnline) {
                continue;
            }
            log.info("sendMessage  memberName:" + message.getReceiverMember().getName());
            log.info("sendMessage  start：" + message.getReceiverMember().getEmailAddress());
            String toEmail = message.getReceiverMember().getEmailAddress();
            if (Strings.isNotBlank(toEmail)) {
                String bodyContent = message.getBodyContent();
                if (Strings.isBlank(bodyContent)) {
                    bodyContent = message.getContent();
                }

                String subject = message.getContent();
                Locale locale = null;
                try {
                    locale = orgManagerDirect.getMemberLocaleById(message.getReceiverMember().getId());
                } catch (Exception e) {
                    log.error("", e);
                }
                if (message.getType() != Constants.UserMessage_TYPE.SYSTEM.ordinal()) {
                    ResourceBundle rb = ResourceBundleUtil.getResourceBundle(Constants.DEFAULT_MESSAGE_RESOURCE, locale);
                    subject = ResourceBundleUtil.getString(rb, "communication.send", message.getSenderMember() != null ? message.getSenderMember().getName() : "");
                }

                StringBuffer mailContent = new StringBuffer();
                mailContent.append(bodyContent);

                String remoteURL = message.getRemoteURL();

                if (Strings.isNotBlank(remoteURL) && messageMailManager.isContentWithLink()) {
                    ResourceBundle rb = ResourceBundleUtil.getResourceBundle(Constants.DEFAULT_MESSAGE_RESOURCE, locale);

                    mailContent.append("<br><br><a href='" + remoteURL + "' target='_blank'>");
                    mailContent.append(ResourceBundleUtil.getString(rb, "common.mail.click2content"));
                    mailContent.append("</a>");
                }

                //kk:邮件增强扩展 start
                /**
                 * -1 走系统标准邮件；1不发邮件；2客开增强
                 */
                int isEmailStrong = -1;

                // 标记是否是 催办
                String messageFlag = (String) message.getMessageContent().getKeys().get(0)[0];
                boolean hastenFlag = StringUtils.equals(messageFlag, "col.hasten");

                // 不是催办走邮件增强
                if (!hastenFlag) {
                    KkEmailStrongManager kkEmailStrongManager = (KkEmailStrongManager) AppContext.getBean("kkEmailStrongManager");
                    if (kkEmailStrongManager != null) {
                        isEmailStrong = kkEmailStrongManager.needEmailStrong(message, messages.length);
                    }
                    log.info("kkEmailStrongManager needEmailStrong return:" + isEmailStrong);
                }

                // end
                if (-1 == isEmailStrong) {
                    // 系统标准邮件
                    messageMailManager.sendMessageByMail(toEmail, subject, mailContent.toString(), message.getCreateDate());
                }
            }
        }
    }

    public int getSortId() {
        return 1;
    }

    public String getName() {
        return "email";
    }

    public String getShowName() {
        return ResourceUtil.getString("message.setting.type.email");
    }

    public boolean isAvailability() {
        return true;
    }

    @Override
    public boolean isShowSetting() {
        return true;
    }

    public String isAllowSetting(User currentUser) {
        if (!messageMailManager.hasSystemMailbox()) {
            return ResourceBundleUtil.getString("com.seeyon.v3x.main.resources.i18n.MainResources", currentUser.getLocale(), "message.setting.email.noSystemMailbox");
        }
        try {
            if (!currentUser.isAdmin() && Strings.isBlank(orgManager.getMemberById(currentUser.getId()).getEmailAddress())) {
                return ResourceBundleUtil.getString("com.seeyon.v3x.main.resources.i18n.MainResources", currentUser.getLocale(), "message.setting.email.noEmailAddress");
            }
        } catch (Exception e) {
            log.error("", e);
        }

        return null;
    }

    public List<Integer> getAllowSettingCategory(User currentUser) {
        return null;
    }

    public boolean isDefaultSend() {
        return false;
    }

}
